package com.li.pm;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import com.li.pm.function.CommonMethod;
import com.li.pm.function.StateManagerConst;
import com.li.pm.function.StateManagerFunction;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.location.Location;
import android.location.LocationManager;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements StateManagerConst,
		SeekBar.OnSeekBarChangeListener {

	private Context context;
	private GridView gridview;
	private Gallery gallery1, gallery2;
	private SeekBar mSeekBar;
	private String[] names;
	private TypedArray icons;
	private CommonMethod common;
	private StateManagerFunction stateManagerService;
	private int mOldBrightness;
	private String strUrl;
	private TextView weatherCodition,weatherDetail;
	private Weather weather;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if (msg.what == 5) {
				weatherCodition.setText(weather.getCondition());
				weatherDetail.setText(weather.getTemp_c()+"\n"+weather.getHumidity()+"\n"+weather.getWind_condition());
			}

		}

	};

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		common = new CommonMethod(context);
		log("oncreate");
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.sm_main);
		gridview = (GridView) findViewById(R.id.gridview);
		stateManagerService = StateManagerFunction.getInstance(context);
		initGridView();
		initGallery1();
		initGallery2();
		initWeather();

	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		common.cancelNotify();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		common.openNotify();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		log("ondestroy");

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		log("onSaveInstanceState");
	}

	private void initWeather(){
		String provider;
		Location location;
		weatherCodition=(TextView) findViewById(R.id.weatherCodition);
		weatherDetail=(TextView) findViewById(R.id.weatherDetail);
		
		LocationManager loctionManager;
		String contextService = Context.LOCATION_SERVICE;
		// 通过系统服务，取得LocationManager对象
		loctionManager = (LocationManager) getSystemService(contextService);
		
		
		provider = LocationManager.GPS_PROVIDER;
		location = loctionManager.getLastKnownLocation(provider);
		if(location==null){
			provider = LocationManager.NETWORK_PROVIDER;
			location = loctionManager.getLastKnownLocation(provider);
		}
		if(location==null){
			provider = LocationManager.PASSIVE_PROVIDER;
			location = loctionManager.getLastKnownLocation(provider);
		}
		if (location == null){
			Log.e("lmf", "location is null");
		}else{
			Log.e("lmf", "location not null");
			int a = (int) (location.getLatitude() * 1000000);
			int b = (int) (location.getLongitude() * 1000000);
			strUrl = "http://www.google.com/ig/api?hl=zh-cn&weather=,,," + a
					+ "," + b;

			new Thread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub

					try {
						URL url = new URL(strUrl);
						// 使用HttpURLConnection打开连接
						HttpURLConnection urlConn = (HttpURLConnection) url
								.openConnection();
						urlConn.setRequestMethod("POST");

						urlConn.setConnectTimeout(6 * 1000);
						if (urlConn.getResponseCode() == 200) {
							Log.e("lmf", "ok");
							weather = PullParseService.getWeather(urlConn
									.getInputStream());
							handler.sendEmptyMessage(5);
						}
						// 得到读取的内�?�?
						// InputStreamReader in = new
						// InputStreamReader(urlConn.getInputStream(),"GBK");
						// 为输出创建BufferedReader
						// BufferedReader buffer = new BufferedReader(in);
						// String inputLine = null;
						// FileOutputStream
						// fos=context.openFileOutput("weatherFile",
						// Context.MODE_PRIVATE);
						// // 使用循环来读取获得的数据
						// while (((inputLine = buffer.readLine()) != null)) {
						// // 我们在每�?��后面加上�?��"\n"来换�?						// fos.write(inputLine.getBytes("GBK"));
						// Log.e("lmf", inputLine);
						// }
						//
						//
						// fos.close();
						// 关闭InputStreamReader
						// in.close();

						// 关闭http连接
						urlConn.disconnect();

					} catch (Exception e) {
						e.printStackTrace();
					}

				}

			}).start();
		}
	}
	
	private void initGridView() {
		int state;

		mSeekBar = (SeekBar) findViewById(R.id.seekbar);
		mSeekBar.setMax(MAXIMUM_BACKLIGHT - MINIMUX_BACKLIGHT);
		mOldBrightness = stateManagerService.getBrightness(0);
		mSeekBar.setProgress(mOldBrightness - MINIMUX_BACKLIGHT);

		mSeekBar.setOnSeekBarChangeListener(this);

		names = getResources().getStringArray(R.array.sm_toggle_names);
		icons = getResources().obtainTypedArray(R.array.sm_toggle_icons);

		// 生成动态数组，并且转入数据
		ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>();

		for (int i = 0; i < 8; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("ItemText", names[i]);// 按序号做ItemText
			state = getPhoneState(i);
			if (state < 2) {
				map.put("ItemImage", icons.getResourceId(i, 0));// 添加图像资源的ID
				if (state == toggle_no) {
					map.put("ItemState", R.color.sm_toggle_no);
				} else {
					map.put("ItemState", R.color.sm_toggle_off);
				}
			} else {
				map.put("ItemState", R.color.sm_toggle_no);
				if (state == STATUS_SOUND_SILENT) {
					map.put("ItemImage", R.drawable.icon_sound_silent);// 添加图像资源的ID
				} else if (state == STATUS_SOUND_VIBRATOR) {
					map.put("ItemImage", R.drawable.icon_sound_vibrate);// 添加图像资源的ID
				} else if (state == STATUS_SOUND_VOLUME) {
					map.put("ItemImage", R.drawable.icon_sound_on);// 添加图像资源的ID
				} else if (state == STATUS_BRIGHT_AUTO) {
					mSeekBar.setVisibility(View.GONE);
					map.put("ItemImage", R.drawable.icon_brightness_auto_on);// 添加图像资源的ID
				} else if (state == STATUS_BRIGHT_MANUAL) {
					mSeekBar.setVisibility(View.VISIBLE);
					map.put("ItemImage", R.drawable.icon_brightness_on);// 添加图像资源的ID

				}
			}

			lstImageItem.add(map);
		}
		// 生成适配器的ImageItem <====> 动态数组的元素，两者一一对应
		SimpleAdapter saImageItems = new SimpleAdapter(this, // 没什么解释
				lstImageItem,// 数据来源
				R.layout.sm_gridview_item,// night_item的XML实现
				// 动态数组与ImageItem对应的子项
				new String[] { "ItemImage", "ItemText", "ItemState" },
				// ImageItem的XML文件里面的一个ImageView,两个TextView ID
				new int[] { R.id.ItemImage, R.id.ItemText, R.id.ItemToggle });
		// 添加并且显示
		gridview.setAdapter(saImageItems);
		// 添加消息处理
		gridview.setOnItemClickListener(new ItemClickListener());

	}

	/**
	 * 0关闭 1打开 2特殊。。。。
	 * 
	 */
	private int getPhoneState(int pos) {

		switch (pos) {
		// wifi
		case 0:

			if (stateManagerService.getWifiState()) {
				return toggle_no;
			} else {
				return toggle_off;
			}
			// 3g
		case 1:

			if (stateManagerService.getPPPState()) {
				return toggle_no;
			} else {
				return toggle_off;
			}
			// 蓝牙
		case 2:

			if (stateManagerService.getBTState()) {
				return toggle_no;
			} else {
				return toggle_off;
			}
			// 重力感应
		case 3:

			if (stateManagerService.getAccelerometerState()) {
				return toggle_no;
			} else {
				return toggle_off;
			}
			// 账户同步
		case 4:

			if (stateManagerService.getSyncState()) {
				return toggle_no;
			} else {
				return toggle_off;
			}
			// 声音
		case 5:

			if (stateManagerService.getSoundState() == AudioManager.RINGER_MODE_SILENT) {
				return STATUS_SOUND_SILENT;
			} else if (stateManagerService.getSoundState() == AudioManager.RINGER_MODE_VIBRATE) {
				return STATUS_SOUND_VIBRATOR;
			} else {
				return STATUS_SOUND_VOLUME;
			}
			// 亮度调节
		case 6:
			if (stateManagerService.getBrightnessMode(0) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
				return STATUS_BRIGHT_AUTO;
			} else {
				return STATUS_BRIGHT_MANUAL;
			}
			// 进入settings
		case 7:
			return toggle_no;
		default:
			return toggle_off;
		}

	}

	private void setPhoneState(int pos, ImageView toggleView,
			ImageView imageView) {

		switch (pos) {
		// wifi
		case 0:
			if (stateManagerService.getWifiState()) {
				toggleView.setImageResource(R.color.sm_toggle_off);
				stateManagerService.setWifiEnabled(false);

			} else {
				toggleView.setImageResource(R.color.sm_toggle_no);
				stateManagerService.setWifiEnabled(true);
			}
			break;
		// APN
		case 1:
			if (stateManagerService.getPPPState()) {
				toggleView.setImageResource(R.color.sm_toggle_off);
				stateManagerService.setPPPEnabled(false);

			} else {
				toggleView.setImageResource(R.color.sm_toggle_no);
				stateManagerService.setPPPEnabled(true);
			}
			break;
		// 蓝牙
		case 2:
			if (stateManagerService.getBTState()) {
				toggleView.setImageResource(R.color.sm_toggle_off);
				stateManagerService.setBTEnabled(false);

			} else {
				toggleView.setImageResource(R.color.sm_toggle_no);
				stateManagerService.setBTEnabled(true);
			}
			break;
		// 重力感应
		case 3:
			if (stateManagerService.getAccelerometerState()) {
				toggleView.setImageResource(R.color.sm_toggle_off);
				stateManagerService.setAccelerometerEnabled(false);

			} else {
				toggleView.setImageResource(R.color.sm_toggle_no);
				stateManagerService.setAccelerometerEnabled(true);
			}
			break;
		// 帐户同步
		case 4:
			if (stateManagerService.getSyncState()) {
				toggleView.setImageResource(R.color.sm_toggle_off);
				stateManagerService.setSyncEnabled(false);

			} else {
				toggleView.setImageResource(R.color.sm_toggle_no);
				stateManagerService.setSyncEnabled(true);
			}
			break;
		// 铃声类型
		case 5:
			if (stateManagerService.getSoundState() == AudioManager.RINGER_MODE_NORMAL) {
				imageView.setImageResource(R.drawable.icon_sound_vibrate);
				stateManagerService
						.setSoundState(AudioManager.RINGER_MODE_VIBRATE);
			} else if (stateManagerService.getSoundState() == AudioManager.RINGER_MODE_VIBRATE) {
				imageView.setImageResource(R.drawable.icon_sound_silent);
				stateManagerService
						.setSoundState(AudioManager.RINGER_MODE_SILENT);
			} else if (stateManagerService.getSoundState() == AudioManager.RINGER_MODE_SILENT) {
				imageView.setImageResource(R.drawable.icon_sound_on);
				stateManagerService
						.setSoundState(AudioManager.RINGER_MODE_NORMAL);
			}
			break;

		// 亮度
		case 6:
			if (stateManagerService.getBrightnessMode(0) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
				imageView.setImageResource(R.drawable.icon_brightness_on);
				stateManagerService.setBrightnessMode(0);
				mSeekBar.setVisibility(View.VISIBLE);
				mSeekBar.setProgress(stateManagerService.getBrightness(50));
			} else {
				imageView.setImageResource(R.drawable.icon_brightness_auto_on);
				stateManagerService
						.setBrightnessMode(Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
				mSeekBar.setVisibility(View.GONE);
			}
			break;
		// 进入设置窗口
		case 7:
			stateManagerService.startSettings();
			break;
		default:
			break;
		}

	}

	private void initGallery1() {
		// 底部滚轮/////////////////////////////////////////////////////////////////////////////////////

		// 生成动态数组，并且转入数据
		ArrayList<HashMap<String, Object>> galleryList = new ArrayList<HashMap<String, Object>>();

		for (int i = 0; i < 12; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("ItemImage", icons.getResourceId(i, 0));// 添加图像资源的ID
			map.put("ItemText", names[i]);// 按序号做ItemText
			galleryList.add(map);
		}

		SimpleAdapter galleryItems = new SimpleAdapter(this, // 没什么解释
				galleryList,// 数据来源
				R.layout.sm_gallery_item,// night_item的XML实现
				// 动态数组与ImageItem对应的子项
				new String[] { "ItemImage", "ItemText" },
				// ImageItem的XML文件里面的一个ImageView,两个TextView ID
				new int[] { R.id.galleryImage, R.id.galleryText });

		gallery1 = (Gallery) this.findViewById(R.id.gallery1);
		gallery1.setAdapter(galleryItems);
		gallery1.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int position, long id) {
				Toast.makeText(MainActivity.this, "gallery---" + position,
						Toast.LENGTH_SHORT).show();
			}
		});

	}

	private void initGallery2() {
		// 底部滚轮/////////////////////////////////////////////////////////////////////////////////////

		// 生成动态数组，并且转入数据
		ArrayList<HashMap<String, Object>> galleryList2 = new ArrayList<HashMap<String, Object>>();

		for (int i = 0; i < 12; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("ItemImage", icons.getResourceId(i, 0));// 添加图像资源的ID
			map.put("ItemText", names[i]);// 按序号做ItemText
			galleryList2.add(map);
		}

		SimpleAdapter galleryItems = new SimpleAdapter(this, // 没什么解释
				galleryList2,// 数据来源
				R.layout.sm_gallery_item,// night_item的XML实现
				// 动态数组与ImageItem对应的子项
				new String[] { "ItemImage", "ItemText" },
				// ImageItem的XML文件里面的一个ImageView,两个TextView ID
				new int[] { R.id.galleryImage, R.id.galleryText });

		gallery2 = (Gallery) this.findViewById(R.id.gallery2);
		gallery2.setAdapter(galleryItems);
		gallery2.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int position, long id) {
				Toast.makeText(MainActivity.this, "gallery---" + position,
						Toast.LENGTH_SHORT).show();
			}
		});

	}

	// 当AdapterView被单击(触摸屏或者键盘)，则返回的Item单击事件
	class ItemClickListener implements OnItemClickListener {
		public void onItemClick(AdapterView<?> arg0,// The AdapterView where the
													// click happened
				View arg1,// The view within the AdapterView that was clicked
				int position,// The position of the view in the adapter
				long arg3// The row id of the item that was clicked
		) {
			// 在本例中position=arg3
			@SuppressWarnings("unchecked")
			HashMap<String, Object> item = (HashMap<String, Object>) arg0
					.getItemAtPosition(position);
			RelativeLayout layout = (RelativeLayout) gridview
					.getChildAt(position);

			ImageView toggleView = (ImageView) layout
					.findViewById(R.id.ItemToggle);
			ImageView imageView = (ImageView) layout
					.findViewById(R.id.ItemImage);

			setPhoneState(position, toggleView, imageView);
		}
	}

	public void log(String mes) {
		Log.e("lmf", mes);
	}

	@Override
	public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
		// TODO Auto-generated method stub
		WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
		layoutParams.screenBrightness = (arg1 + MINIMUX_BACKLIGHT) / 255.0f;// b是亮度
		getWindow().setAttributes(layoutParams);
		stateManagerService.setBrightness(arg1 + MINIMUX_BACKLIGHT);
	}

	@Override
	public void onStartTrackingTouch(SeekBar arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStopTrackingTouch(SeekBar arg0) {
		// TODO Auto-generated method stub

	}

}